package cn.labelnet.android.roomdb.base.data

import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.Room
import android.arch.persistence.room.migration.Migration
import android.content.Context
import android.util.Log
import cn.labelnet.android.roomdb.base.data.dao.BookDao
import cn.labelnet.android.roomdb.base.data.dao.UserDao
import cn.labelnet.android.roomdb.base.data.database.AppDataBase

/**
 * Created by yuan on 02/08/2017.
 * db 操作类
 */
class DbHelper constructor(context: Context) {

    var appDb: AppDataBase? = null
    val DB_NAME = "room_test_db.db"

    /**
     * 初始化 db
     */
    init {
        appDb = Room.databaseBuilder(context,
                AppDataBase::class.java,
                DB_NAME)
                .build()
                //.addMigrations(MigrateDb(1, 2))
    }

    /**
     * 获取 user dao
     */
    fun getUserDao(): UserDao {
        return appDb!!.userDao()
    }

    /**
     * 获取 book dao
     */
    fun getBookDao(): BookDao {
        return appDb!!.bookDao()
    }


    /**
     * 单例实现
     */
    companion object {

        var INSTANCE: DbHelper? = null

        fun init(context: Context): DbHelper {
            if (INSTANCE == null) {
                synchronized(DbHelper::class) {
                    if (INSTANCE == null) {
                        INSTANCE = DbHelper(context)
                    }
                }
            }
            return INSTANCE!!
        }

    }

    /**
     * 关闭数据库
     */
    fun onDestory() {
        if (appDb != null) {
            appDb!!.close()
        }
    }

    /**
     * 版本合并
     */
    class MigrateDb(startVersion: Int, endVersion: Int) : Migration(startVersion, endVersion) {
        override fun migrate(database: SupportSQLiteDatabase?) {
            Log.v("DbHelper", "migrate")
        }
    }

}